package com.woniuxy.controller;

import com.woniuxy.entity.User;
import com.woniuxy.entity.utils.ResponseEntity;
import com.woniuxy.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.woniuxy.utils.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 马宇航
 * @Description: 登录用的接口
 * @DateTime: 22/10/14/0014 12:04
 * @Component: 成都蜗牛学苑
 **/
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    AuthService authService;
    @Autowired
    RedisTemplate redisTemplate;
    @GetMapping("/login")
    public ResponseEntity login(User user){
       User duser = authService.findByUser(user);
       //密码判断
        if (duser.getPassword().equals(user.getPassword())){
            //成功就可以生产token，和refreshtoken，并存入redis中
            String token = JWTUtils.generateToken(user.getUsername());
            //创建对应的刷新 refreshToken
            String refreshToken = UUID.randomUUID().toString();
            //将token和refreshToken纯如redis中,map是用来当redis的value
            Map<String,Object> data = new HashMap<>();
            data.put("username",duser.getUsername());
            //为什么这里只存储用户名，没有存token，因为后面在网关里面，要用这个用户名去校验前端的token是否正确。
            redisTemplate.opsForHash().putAll(refreshToken,data);
            //设置刷新token的过期时间
            redisTemplate.expire(refreshToken,1, TimeUnit.HOURS);
            ResponseEntity response = new ResponseEntity(data);
            response.put("token",token);
            response.put("refresh",refreshToken);
            return response;
        }
       return ResponseEntity.ERROR;
    }
}
